package dcsinstnce.server.interfaces.impl;

import java.util.Hashtable;

import dcsinstnce.server.accessers.DataReader;
import dcsinstnce.server.accessers.impl.DataReaderImpl;
import dcsinstnce.server.interfaces.SuscriberOperations;
import dcsinstnce.server.operations.Operation;

public class SuscriberImpl implements SuscriberOperations{
	private Hashtable<String, DataReaderImpl> listeners;
	private Hashtable<String, Operation> operations;
	/**
	 * constructeur
	 */
	public SuscriberImpl() {
		operations = new Hashtable<String, Operation>();
		listeners = new Hashtable<String, DataReaderImpl>();
	}
	@Override
	public String getTopicName(short i){
		return getDataReaderListenerName(i);
	}
	@Override
	public DataReader getDataReaderListener(short i) {
		return (DataReader) listeners.get(getDataReaderListenerName(i));
	}
	/**
	 * 
	 * @param i : position du datareader
	 * @return : datareader
	 */
	public DataReaderImpl getDataReaderListener1(short i) {
		return listeners.get(getDataReaderListenerName(i));
	}
	@Override
	public DataReader getDataReaderListenerByTopicName(String topicName) {
		return (DataReader)listeners.get(topicName);
	}
	public DataReaderImpl getDataReaderListenerByTopicName1(String topicName) {
		return listeners.get(topicName);
	}
	@Override
	public void publish(String topicName, Operation operation) {
		DataReaderImpl listener = listeners.get(topicName);
		operations.put(topicName, operation);
		
		if(listener != null)
			listener.signale();
	}
	@Override
	public Operation read(String topicName) {
		if(operations.containsKey(topicName)){
			return operations.remove(topicName);
		}
		return null;
	}
	/**
	 * 
	 * @param topicName : nom du topic correspondant au listener à ajouter
	 * @param listener : listener à ajouter
	 * @return : le subscriber lui même
	 */
	public SuscriberImpl addDataReaderListener(String topicName, DataReaderImpl listener) {
		this.listeners.put(topicName, listener);		
		return this;
	}
	@Override
	public short getListenerCount() {
		return (short) listeners.size();
	}
	/**
	 * 
	 * @param i : position du listener
	 * @return : nom du listener à la position i
	 */
	public String getDataReaderListenerName(short i) {
		return (String)listeners.keySet().toArray()[i];
	}
	/**
	 * 
	 * @param i : position de l'opération
	 * @return : operation à la position i
	 */
	public Operation getOperation(short i) {
		return operations.get(getOperationName(i));
	}
	/**
	 * 
	 * @param i : position de l'opération
	 * @return : le nom du topic correspondant à l'opération
	 */
	public String getOperationName(short i) {
		return (String)operations.keySet().toArray()[i];
	}
	/**
	 * 
	 * @param i : position du listener
	 */
	public void removeListener(int i){
		listeners.remove(getDataReaderListenerName((short)i));
	}
}
